import os
import sys
from datetime import datetime

# 添加项目根目录到Python路径
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

# 导入必要的模块
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from werkzeug.security import generate_password_hash

# 数据库文件路径
DB_PATH = 'C:\\Users\\25089\\PycharmProjects\\人力资源管理系统\\instance\\hrm.db'

# 创建Flask应用实例
app = Flask(__name__)

# 配置数据库
app.config['SECRET_KEY'] = 'hrm_system_secret_key'
# 先处理数据库路径，避免f-string中的反斜杠问题
formatted_db_path = DB_PATH.replace('\\', '/')
app.config['SQLALCHEMY_DATABASE_URI'] = f'sqlite:///{formatted_db_path}'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False

# 初始化数据库
db = SQLAlchemy(app)

# 定义数据模型
class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(50), unique=True, nullable=False)
    password_hash = db.Column(db.String(128), nullable=False)
    role = db.Column(db.String(20), nullable=False, default='employee')  # 角色：admin 或 employee
    name = db.Column(db.String(100), nullable=True)  # 用户姓名
    gender = db.Column(db.String(10))  # 性别：male 或 female
    birth_date = db.Column(db.Date)  # 出生日期
    phone = db.Column(db.String(20))  # 联系电话
    email = db.Column(db.String(100), unique=True)  # 邮箱
    department_id = db.Column(db.Integer, db.ForeignKey('department.id'), nullable=True)  # 部门ID
    position = db.Column(db.String(100))  # 职位
    address = db.Column(db.Text)  # 地址
    avatar = db.Column(db.String(255))  # 头像地址
    created_at = db.Column(db.DateTime, default=datetime.utcnow)
    updated_at = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)
    
    def set_password(self, password):
        self.password_hash = generate_password_hash(password)

class Department(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(100), unique=True, nullable=False)
    created_at = db.Column(db.DateTime, default=datetime.utcnow)
    updated_at = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)

class Employee(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=True)  # 关联用户ID
    name = db.Column(db.String(100), nullable=False)
    gender = db.Column(db.String(10))
    phone = db.Column(db.String(20))
    position = db.Column(db.String(100))
    department_id = db.Column(db.Integer, db.ForeignKey('department.id'), nullable=True)
    created_at = db.Column(db.DateTime, default=datetime.utcnow)
    updated_at = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)
    
    # 与用户的关联
    user = db.relationship('User', backref='employee', lazy=True)

class Attendance(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    employee_id = db.Column(db.Integer, db.ForeignKey('employee.id'), nullable=False)
    date = db.Column(db.Date, nullable=False)
    check_in_time = db.Column(db.Time)
    check_out_time = db.Column(db.Time)
    status = db.Column(db.String(20), default='present')
    created_at = db.Column(db.DateTime, default=datetime.utcnow)
    updated_at = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)

class Performance(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    employee_id = db.Column(db.Integer, db.ForeignKey('employee.id'), nullable=False)
    period = db.Column(db.String(20), nullable=False)
    score = db.Column(db.Float, nullable=False)
    comments = db.Column(db.Text)
    evaluator_id = db.Column(db.Integer, db.ForeignKey('employee.id'), nullable=False)
    created_at = db.Column(db.DateTime, default=datetime.utcnow)
    updated_at = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)

# 主函数
def main():
    # 检查并删除旧的数据库文件
    if os.path.exists(DB_PATH):
        print(f"正在尝试删除旧的数据库文件: {DB_PATH}")
        try:
            os.remove(DB_PATH)
            print("旧的数据库文件已成功删除")
        except PermissionError:
            print("\n错误：无法删除数据库文件，因为它正在被另一个程序使用。")
            print("解决方法：")
            print("1. 关闭所有可能正在访问该数据库的程序（如PyCharm、Python解释器等）")
            print("2. 手动删除文件: " + DB_PATH)
            print("3. 再次运行此脚本")
            print("\n如果仍然无法删除，请重启电脑后再试。")
            sys.exit(1)
    else:
        print("未找到旧的数据库文件，将创建新的数据库文件")
    
    # 确保instance目录存在
    instance_dir = os.path.dirname(DB_PATH)
    if not os.path.exists(instance_dir):
        print(f"正在创建instance目录: {instance_dir}")
        os.makedirs(instance_dir)
    
    # 在应用上下文中创建数据库表和用户
    with app.app_context():
        # 创建所有数据库表
        print("正在创建数据库表...")
        db.create_all()
        print("数据库表创建成功")
        
        # 创建部门数据
        print("正在创建部门数据...")
        departments = [
            Department(name='人力资源部'),
            Department(name='技术部'),
            Department(name='市场部'),
            Department(name='财务部'),
            Department(name='运营部'),
            Department(name='销售部')
        ]
        db.session.add_all(departments)
        db.session.commit()
        print("部门数据创建成功")
        
        # 创建用户账号
        print("正在创建用户账号...")
        users = [
            # 管理员账号
            User(
                username='admin',
                role='admin',
                name='系统管理员',
                gender='男',
                phone='13800000001',
                email='admin@example.com',
                department_id=1,  # 人力资源部
                position='人力资源总监',
                address='北京市朝阳区'
            ),
            # 技术部员工
            User(
                username='zhangsan',
                role='employee',
                name='张三',
                gender='男',
                phone='13800000002',
                email='zhangsan@example.com',
                department_id=2,  # 技术部
                position='高级开发工程师',
                address='北京市海淀区'
            ),
            User(
                username='lisi',
                role='employee',
                name='李四',
                gender='女',
                phone='13800000003',
                email='lisi@example.com',
                department_id=2,  # 技术部
                position='前端开发工程师',
                address='北京市西城区'
            ),
            # 市场部员工
            User(
                username='wangwu',
                role='employee',
                name='王五',
                gender='男',
                phone='13800000004',
                email='wangwu@example.com',
                department_id=3,  # 市场部
                position='市场经理',
                address='北京市东城区'
            ),
            # 财务部员工
            User(
                username='zhaoliu',
                role='employee',
                name='赵六',
                gender='女',
                phone='13800000005',
                email='zhaoliu@example.com',
                department_id=4,  # 财务部
                position='财务专员',
                address='北京市丰台区'
            ),
            # 运营部员工
            User(
                username='qianqi',
                role='employee',
                name='钱七',
                gender='男',
                phone='13800000006',
                email='qianqi@example.com',
                department_id=5,  # 运营部
                position='运营专员',
                address='北京市石景山区'
            ),
            # 销售部员工
            User(
                username='sunba',
                role='employee',
                name='孙八',
                gender='女',
                phone='13800000007',
                email='sunba@example.com',
                department_id=6,  # 销售部
                position='销售代表',
                address='北京市通州区'
            )
        ]
        
        # 设置密码
        users[0].set_password('admin123')  # 管理员密码
        for i in range(1, len(users)):
            users[i].set_password('user123')  # 员工密码
        
        # 添加到会话并提交
        db.session.add_all(users)
        db.session.commit()
        
        print("用户账号创建成功")
        
        # 创建员工数据
        print("正在创建员工数据...")
        employees = [
            Employee(
                user_id=2,  # 张三的用户ID
                name='张三',
                gender='男',
                phone='13800000002',
                position='高级开发工程师',
                department_id=2
            ),
            Employee(
                user_id=3,  # 李四的用户ID
                name='李四',
                gender='女',
                phone='13800000003',
                position='前端开发工程师',
                department_id=2
            ),
            Employee(
                user_id=4,  # 王五的用户ID
                name='王五',
                gender='男',
                phone='13800000004',
                position='市场经理',
                department_id=3
            ),
            Employee(
                user_id=5,  # 赵六的用户ID
                name='赵六',
                gender='女',
                phone='13800000005',
                position='财务专员',
                department_id=4
            ),
            Employee(
                user_id=6,  # 钱七的用户ID
                name='钱七',
                gender='男',
                phone='13800000006',
                position='运营专员',
                department_id=5
            ),
            Employee(
                user_id=7,  # 孙八的用户ID
                name='孙八',
                gender='女',
                phone='13800000007',
                position='销售代表',
                department_id=6
            )
        ]
        
        db.session.add_all(employees)
        db.session.commit()
        print("员工数据创建成功")
        
        # 创建考勤数据
        print("正在创建考勤数据...")
        from datetime import date, time, timedelta
        
        attendance_records = []
        employee_ids = [emp.id for emp in employees]
        
        # 为每个员工创建最近30天的考勤记录
        for emp_id in employee_ids:
            for i in range(30):
                attendance_date = date.today() - timedelta(days=i)
                
                # 随机生成考勤状态
                import random
                status_options = ['present', 'late', 'absent', 'early']
                status = random.choices(status_options, weights=[70, 15, 10, 5])[0]
                
                if status == 'present':
                    check_in = time(9, random.randint(0, 30))  # 9:00-9:30
                    check_out = time(18, random.randint(0, 30))  # 18:00-18:30
                elif status == 'late':
                    check_in = time(9, random.randint(31, 59))  # 9:31-9:59
                    check_out = time(18, random.randint(0, 30))
                elif status == 'early':
                    check_in = time(9, random.randint(0, 30))
                    check_out = time(17, random.randint(0, 59))  # 17:00-17:59
                else:  # absent
                    check_in = None
                    check_out = None
                
                attendance_records.append(Attendance(
                    employee_id=emp_id,
                    date=attendance_date,
                    check_in_time=check_in,
                    check_out_time=check_out,
                    status=status
                ))
        
        db.session.add_all(attendance_records)
        db.session.commit()
        print("考勤数据创建成功")
        
        # 创建绩效数据
        print("正在创建绩效数据...")
        performance_records = []
        
        # 为每个员工创建最近4个季度的绩效记录
        quarters = ['2024-Q1', '2024-Q2', '2024-Q3', '2024-Q4']
        for emp_id in employee_ids:
            for quarter in quarters:
                import random
                score = random.uniform(75, 95)  # 75-95分
                comments = f"{quarter}季度表现{'优秀' if score > 90 else '良好' if score > 85 else '一般'}"
                
                performance_records.append(Performance(
                    employee_id=emp_id,
                    period=quarter,
                    score=round(score, 1),
                    comments=comments,
                    evaluator_id=1  # 管理员作为评估人
                ))
        
        db.session.add_all(performance_records)
        db.session.commit()
        print("绩效数据创建成功")
        
        print("\n=== 初始化数据创建完成 ===")
        print("\n测试账号信息：")
        print("管理员账号: username=admin, password=admin123")
        print("员工账号: username=zhangsan, password=user123")
        print("员工账号: username=lisi, password=user123")
        print("员工账号: username=wangwu, password=user123")
        print("员工账号: username=zhaoliu, password=user123")
        print("员工账号: username=qianqi, password=user123")
        print("员工账号: username=sunba, password=user123")
        print("\n数据统计：")
        print(f"- 部门数量: {len(departments)}")
        print(f"- 用户数量: {len(users)}")
        print(f"- 员工数量: {len(employees)}")
        print(f"- 考勤记录: {len(attendance_records)}")
        print(f"- 绩效记录: {len(performance_records)}")
        print("\n请注意：首次登录后请修改密码以保证账号安全。")

if __name__ == '__main__':
    main()